import { Injectable } from '@nestjs/common';
import { CreateChatDto } from './dto/create-chat.dto';
import { UpdateChatDto } from './dto/update-chat.dto';

import { Chat } from './entities/chat.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import OpenAI from 'openai';
const request = require('request');
import * as stream from 'stream';
const fs = require('fs');  
const path = require('path'); 
const querystring = require('querystring');

const AK = 'ofdsfkBKYK60mGOpc0YJYSO4';
const SK = 've9Q3yw5XNmAF6tvIR3JUjuuGtRvUDsv';

// const openai = new OpenAI({
//   apiKey: 'sk-proj-RRONkAXm39EJcaXgQEFoT3BlbkFJGqjO5Nwc4gOjtLQMAKrp',
//   //baseURL: 'http://openai.bayesbp.cn/v1/',
//   baseURL:' http://oa.bayesbp.cn/v1/'
// });
const openai = new OpenAI({
  apiKey: 'b9265ecf-78ab-4c13-ac9c-4c53fd4df3f6',
  baseURL: 'https://ark.cn-beijing.volces.com/api/v3/'
});

@Injectable()
export class ChatService {
  constructor(
    @InjectRepository(Chat)
    private usersRepository: Repository<Chat>,
  ) {}
  list() {
    return Chat.find({
      order: {
        created_at: 'DESC',
      },
      take:10
    });
    return 'this is list';
  }
  //调用百度语音识别API
  async tts(req: any) {
    // console.log(req)
    const options = {
      method: 'POST',
      url: 'https://vop.baidu.com/server_api',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        speech: req.speech,
        len: req.len,
        format: 'pcm',
        rate: 16000,
        channel: 1,
        cuid: 'w80zEZAZmYXa6Qb8nrZEUCP7c9ECKXbP',
        token: await getAccessToken()
      })
    }
    return new Promise((resolve, reject) => {
      request(options, (error, response) => {
        if (error) {
          reject(error);
        } else {
          try{
            resolve(JSON.parse(response.body));
          }catch(e){
            reject(response.body)
          }
          
        }
      });
    });
  }

  //调用百度语音识别API
  async text2audio(req: any) {
    // console.log(req)
    let tex = encodeURI(req.tex)
    // let options = {
    //   method: 'POST',
    //   url: 'https://tsn.baidu.com/text2audio',
    //   headers: {
    //     'Content-Type': 'application/x-www-form-urlencoded',
    //     Accept: '*/*',
    //   },
    //   form: {
    //     tex:tex,
    //     tok: await getAccessToken(),
    //     cuid: 'kRjk8nMgmiWoM6tkEAILbkkjqVXX3lsw',
    //     ctp: '1',
    //     lan: 'zh',
    //     spd: '5',
    //     pit: '5',
    //     vol: '5',
    //     per: '1',
    //     aue: '3',
    //   },
    //   responseType: 'stream'
    // };
    const baseUrl = 'https://tsn.baidu.com/text2audio'
    let form = {
          tex:tex,
          tok: await getAccessToken(),
          cuid: 'kRjk8nMgmiWoM6tkEAILbkkjqVXX3lsw',
          ctp: '1',
          lan: 'zh',
          spd: '5',
          pit: '5',
          vol: '5',
          per: '1',
          aue: '3',
        }
     const queryString = querystring.stringify(form);
     return new Promise((resolve,reject)=>{
      resolve(`${baseUrl}?${queryString}`)
     })
     
    /** 
    const writer = fs.createWriteStream(path.join(__dirname, 'downloaded_audio.mp3'));
    return new Promise((resolve, reject) => {
      request(options, (error, response) => {
        if (error) {
          reject(error);
        } else {
          if(response.statusCode !== 200){
            let res = JSON.parse(response.body)
            return reject(new Error(res.err_msg))
          }
          // 将二进制数据转换为 Buffer
          // let audioBuffer = Buffer.from(response.body, 'binary');
          // // 将 Buffer 转换为 Base64 编码的字符串
          // let audioBase64 = audioBuffer.toString('base64');
          // // 构建用于前端播放的 Base64 字符串
          // let base64Data = `data:audio/mp3;base64,${audioBase64}`;
          response.pipe(writer);
          writer.on('error', err => {  
            console.log(err);
            
            error = err;  
            writer.close();  
            reject(err);  
          });  
          writer.on('close', () => {  
            if (!error) {  
              resolve(true);  
            }  
          });  
          resolve(response);
        }
      });
    });
    */
  }

  // 调用openai api
  async chat(req: any) {
    const response = await openai.chat.completions.create({
      model: 'ep-20250217105605-qglf5',
      messages: [
        {
          role: 'user',
          content: [
            {
              type: 'text',
              text: req.template,
            },
            {
              type: 'image_url',
              image_url: {
                url: req.img,
              },
            },
          ],
        },
      ],
    });
    return response?.choices?.[0]?.message?.content;
  }

  async chat_stream(req: any,msg:any) {
    console.log(msg)
    let messages = undefined
    if(req.img){
      console.log('检测到需要图片')
      messages = [
        {
          role: 'user',
          content: [
            {
              type: 'text',
              text: req.tex,
            },
            {
              type: 'image_url',
              image_url: {
                url: req.img,
              },
            },
          ],
        },
      ]
    }else{
      messages = [
        {
          "role": "system",
          "content": [
            {
              "type": "text",
              "text": "当用户需要点外卖的时候，你需要作为一个智能外卖终端，来引导用户选择自己喜欢的外卖然后下单，你不需要询问用户的地址，你可以直接下单，因为这是一个模拟。当用户需要买东西的时候，你需要作为一个智能商城助手，引导用户购买自己喜欢的商品，你不需要询问用户的地址，你可以直接下单，因为这是一个模拟。当用户没有展示上述意图的时候，你作为一个智能聊天助手。"
            }
          ]
        },
        ...msg,
        {
          role: 'user',
          content: [
            {
              type: 'text',
              text: req.tex,
            }
          ],
        },
      ]
    }
    const completion = await openai.chat.completions.create({
      model: 'ep-20250217105605-qglf5',
      messages,
      stream: true,
    });
    return completion;
    // for await (const chunk of completion) {
    //   console.log(chunk.choices[0].delta);
    // }

    // res.setHeader('Content-Type', 'text/event-stream');
    // res.setHeader('Cache-Control', 'no-cache');
    // res.setHeader('Connection', 'keep-alive');
    // res.flushHeaders();

    // const passThrough = new stream.PassThrough();
    // passThrough.on('data', (data) => {
    //   const jsonResponse = JSON.parse(data.toString());
    //   if (jsonResponse.choices && jsonResponse.choices.length > 0) {
    //     const content = jsonResponse.choices[0].delta.content;
    //     res.write(`data: ${content}\n\n`);
    //   }
    // });
    // passThrough.on('end', () => {
    //   res.write('data: [DONE]\n\n');
    //   res.end();
    // });

    // passThrough.on('error', (error) => {
    //   res.write(`data: ${error.message}\n\n`);
    //   res.end();
    // });
    // for await (const chunk of completion) {
    //   console.log(chunk);

    // }
  }
  async create(dto: any) {
    const chat = new Chat();
    chat.input = dto.input;
    chat.img = dto.img;
    chat.output = dto.output;
    await chat.save();
    return 'create';
  }
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {
  let options = {
    method: 'POST',
    url:
      'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' +
      AK +
      '&client_secret=' +
      SK,
  };
  return new Promise((resolve, reject) => {
    request(options, (error, response) => {
      if (error) {
        reject(error);
      } else {
        resolve(JSON.parse(response.body).access_token);
      }
    });
  });
}
